package com.zhht.htzx.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.binding_recyclerview.BR;
import com.nsgf.library.data.bean.LibraryInfo;
import com.nsgf.library.data.bean.ProductBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.glide.GlideImgManager;
import com.nsgf.library.glide.GlideRoundTransform;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.zhht.htzx.R;
import com.zhht.htzx.utils.SharePosterUtils;

import java.util.ArrayList;
import java.util.List;

public class SharePosterActivity extends BaseActivity {
    private static final int PICK_POSTER_REQUEST = 1;
    private ViewPager2 viewPagerPoster;
    private Button btnSavePoster;
    private Button btnShare;

    private List<LibraryInfo> posterUrls = new ArrayList<>();
    private List<Bitmap> posterBitmaps;
    private Bitmap qrCodeBitmap;
    private Bitmap finalPosterBitmap;
    private Uri posterUri;
    private int currentPosterIndex = 0;

    private StateHolder mStates;
    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(StateHolder.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_share_poster, BR.vm, mStates);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getLifecycle().addObserver(mAccountRequester);
        mStates.titleBar.set("邀请有礼");
        initViews();
        initData();
    }

    private void initViews() {
        viewPagerPoster = findViewById(R.id.view_pager_poster);
        btnSavePoster = findViewById(R.id.btn_save_poster);
        btnShare = findViewById(R.id.btn_share);
    }

    private void initData() {
        posterBitmaps = new ArrayList<>();
        mAccountRequester.invitedGift();
        mAccountRequester.getLibraryList().observe(this, new Observer<ResponseStatus<List<LibraryInfo>>>() {
            @Override
            public void onChanged(ResponseStatus<List<LibraryInfo>> listResponseStatus) {
                if (listResponseStatus.getResponseCode() == 0) {
                    posterUrls.addAll(listResponseStatus.getData());
                    // 初始化posterBitmaps列表，确保有足够的空间
                    for (int i = 0; i < posterUrls.size(); i++) {
                        posterBitmaps.add(null);
                    }
                    initListeners();
                    setupViewPager();
                }

            }
        });
    }

    private void initListeners() {
        btnSavePoster.setOnClickListener(v -> savePosterToGallery());
        btnShare.setOnClickListener(v -> sharePoster());
    }

    private void setupViewPager() {
        PosterAdapter adapter = new PosterAdapter();
        viewPagerPoster.setAdapter(adapter);
        // 监听页面切换
        viewPagerPoster.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                currentPosterIndex = position;
                // 自动为当前海报生成二维码
                autoGenerateQRCode();
            }
        });
    }

    /**
     * 自动为当前海报生成二维码
     */
    private void autoGenerateQRCode() {
        if (posterBitmaps.isEmpty() || currentPosterIndex >= posterBitmaps.size()) {
            return;
        }

        Bitmap posterBitmap = posterBitmaps.get(currentPosterIndex);
        if (posterBitmap == null) {
            return;
        }

        // 生成二维码
        String shareUrl = "https://zhonghehuitong.com.cn/home/register.html?invite_code=" + UserInfo.getInstance().getId();
        qrCodeBitmap = SharePosterUtils.generateQRCode(shareUrl);

        if (qrCodeBitmap == null) {
            return;
        }

        // 缩放二维码到合适大小（这里设置为海报宽度的1/4）
        int qrSize = posterBitmap.getWidth() / 4;
        qrCodeBitmap = SharePosterUtils.scaleQRCode(qrCodeBitmap, qrSize);

        // 计算二维码位置（这里放在右下角，留出边距）
        int margin = 30;
        int x = posterBitmap.getWidth() - qrCodeBitmap.getWidth() - margin;
        int y = posterBitmap.getHeight() - qrCodeBitmap.getHeight() - margin;

        // 直接在海报上绘制二维码
        boolean success = SharePosterUtils.drawQRCodeOnPoster(posterBitmap, qrCodeBitmap, x, y);

        if (success) {
            // 使用修改后的海报作为最终海报
            finalPosterBitmap = posterBitmap;

            // 清除之前的保存URI
            posterUri = null;
        } else {
            // 如果直接绘制失败，使用原来的合成方法
            finalPosterBitmap = SharePosterUtils.composePoster(posterBitmap, qrCodeBitmap, x, y);

        }
    }

    private void savePosterToGallery() {
        if (posterBitmaps.isEmpty() || currentPosterIndex >= posterBitmaps.size()) {
            Toast.makeText(this, "请先选择海报", Toast.LENGTH_SHORT).show();
            return;
        }

        Bitmap currentPoster = posterBitmaps.get(currentPosterIndex);
        if (currentPoster == null) {
            Toast.makeText(this, "海报加载中，请稍候", Toast.LENGTH_SHORT).show();
            return;
        }

        // 直接保存当前海报到系统相册
        posterUri = SharePosterUtils.saveImageToSystemGallery(this, currentPoster, "share_poster_" + System.currentTimeMillis());
        if (posterUri != null) {
            Toast.makeText(this, "海报已保存到系统相册", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "保存失败，请检查存储权限", Toast.LENGTH_SHORT).show();
        }
    }

    private void sharePoster() {
        if (posterBitmaps.isEmpty() || currentPosterIndex >= posterBitmaps.size()) {
            Toast.makeText(this, "请先选择海报", Toast.LENGTH_SHORT).show();
            return;
        }

        Bitmap currentPoster = posterBitmaps.get(currentPosterIndex);
        if (currentPoster == null) {
            Toast.makeText(this, "海报加载中，请稍候", Toast.LENGTH_SHORT).show();
            return;
        }

        // 直接保存当前海报到系统相册并分享
        posterUri = SharePosterUtils.saveImageToSystemGallery(this, currentPoster, "share_poster_" + System.currentTimeMillis());
        if (posterUri != null) {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("image/png");
            shareIntent.putExtra(Intent.EXTRA_STREAM, posterUri);
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(Intent.createChooser(shareIntent, "分享海报"));
        } else {
            Toast.makeText(this, "分享失败，请检查存储权限", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 回收Bitmap
        for (Bitmap bitmap : posterBitmaps) {
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
        }
        if (qrCodeBitmap != null && !qrCodeBitmap.isRecycled()) {
            qrCodeBitmap.recycle();
        }
        if (finalPosterBitmap != null && !finalPosterBitmap.isRecycled()) {
            finalPosterBitmap.recycle();
        }
    }

    // ViewPager2适配器
    private class PosterAdapter extends RecyclerView.Adapter<PosterAdapter.PosterViewHolder> {

        @NonNull
        @Override
        public PosterAdapter.PosterViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            ImageView imageView = new ImageView(parent.getContext());
            imageView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            return new PosterViewHolder(imageView);
        }

        @Override
        public void onBindViewHolder(@NonNull PosterViewHolder holder, @SuppressLint("RecyclerView") int position) {
            String imageUrl = posterUrls.get(position).getUrl();

            Glide.with(SharePosterActivity.this)
                    .asBitmap()
                    .transform(new CenterCrop(), new GlideRoundTransform(SharePosterActivity.this, 10))
                    .load(imageUrl)
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(@NonNull Bitmap resource, Transition<? super Bitmap> transition) {
                            // 确保Bitmap是可变的，以便直接在上面绘制二维码
                            Bitmap mutableBitmap = resource.copy(Bitmap.Config.ARGB_8888, true);
                            holder.imageView.setImageBitmap(mutableBitmap);

                            // 安全地保存可变的Bitmap到列表
                            synchronized (posterBitmaps) {
                                // 确保列表有足够的空间
                                while (posterBitmaps.size() <= position) {
                                    posterBitmaps.add(null);
                                }
                                posterBitmaps.set(position, mutableBitmap);
                            }

                            // 如果是当前选中的海报，自动生成二维码
                            if (position == currentPosterIndex) {
                                autoGenerateQRCode();
                            }
                        }
                    });
        }

        @Override
        public int getItemCount() {
            return posterUrls.size();
        }

        class PosterViewHolder extends RecyclerView.ViewHolder {
            ImageView imageView;

            PosterViewHolder(@NonNull View itemView) {
                super(itemView);
                imageView = (ImageView) itemView;
            }
        }
    }
} 